package com.echofeng.common.ui.base;

import android.annotation.SuppressLint;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.echofeng.common.R;
import com.echofeng.common.config.AppManager;
import com.echofeng.common.config.MessageEvent;
import com.echofeng.common.ui.widget.dialog.LoadingDialog;
import com.echofeng.common.utils.MyToast;
import com.echofeng.common.utils.NetUtil;
import com.echofeng.common.utils.helper.LocaleManager;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

public abstract class BaseNoRestartActivity extends AppCompatActivity {

    protected String TAG = this.getClass().getSimpleName();
    protected BaseNoRestartActivity mActivity;
    protected RxPermissions rxPermissions;
    protected int pageNum = 1;
    protected int pageNum2 = 1;
    //这里用来判断重复频繁点击问题
    protected boolean clickable = true;
    protected Context context;
    protected View barView;
    //toolbar（如果存在）设置方法
    protected TextView titleTv, optionTv;
    ImageView backIv;
    private LoadingDialog loadingDialog;

    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getApplicationContext();
        EventBus.getDefault().register(this);
        //竖屏
        AppManager.getAppManager().addActivity(this);
        //避免5.0修改不到顶部颜色导致看不到顶部的状态
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        //状态栏中的文字颜色和图标颜色，需要android系统6.0以上，而且目前只有一种可以修改（一种是深色，一种是浅色即白色）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //修改为深色，因为我们把状态栏的背景色修改为主题色白色，默认的文字及图标颜色为白色，导致看不到了。
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }

        setContentView(this.getLayoutId());

        mActivity = this;
        rxPermissions = new RxPermissions(this);
        initBar();
        initView();
        initData();
    }

    //定义视图抽象方法
    protected abstract int getLayoutId();

    //定义初始化抽象方法
    protected abstract void initView();
    //设置数据的抽象方法
    protected abstract void initData();

    @NotNull
    public String getStringValues(int resId) {
        return getResources().getString(resId);
    }

    //默认不开启软键盘
    private void onInputDef() {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    }

    public void setTextUnderLine(TextView targetView) {
        targetView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        targetView.getPaint().setAntiAlias(true);//抗锯齿
    }

    @NotNull
    public int getColorValues(int resId) {
        return ContextCompat.getColor(this, resId);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(LocaleManager.setLocale(base));
    }


    public void copyString(String string) {
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        cm.setText(string);
        Toast.makeText(mActivity, getResources().getString(R.string.toast_copy_success), Toast.LENGTH_SHORT).show();
    }

    /**
     * 是否有网络
     *
     * @return
     */
    public boolean hasNet() {
        int state = NetUtil.getNetWorkState(this);
        if (state == NetUtil.NETWORK_NONE) {
            MyToast.showToast(getResources().getString(R.string.toast_no_net));
            return false;
        } else {
            return true;
        }
    }

    public boolean isGetPermission(String[] permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!checkPermission(permissions)) {
//                requestPermissions(permissions, 100);
                ActivityCompat.requestPermissions(this, permissions, 100);
                return false;
            } else if (checkPermission(permissions)) {
                return true;
            } else {  // 后续有其余情形可补充
                return false;
            }
        } else {
            return false;
        }
    }

    public boolean checkPermission(String[] permissions) {
        boolean granted = true;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for (String permission : permissions) {
                granted = checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
                if (!granted) {
                    break;
                }
            }
        }
        return granted;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {/* Do something */}

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dismissLoading();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    /**
     * 使用SP 的尺寸不受 系统字体的影响而改变，防止出现字体放大而出现的布局问题
     *
     * @return
     */
    @Override
    public Resources getResources() {//还原字体大小
        Resources res = super.getResources();
        //非默认值
        if (res.getConfiguration().fontScale != 1) {
            Configuration newConfig = new Configuration();
            newConfig.setToDefaults();//设置默认
            res.updateConfiguration(newConfig, res.getDisplayMetrics());
        }
        return res;
    }

    /**
     * 初始化bar
     */
    private void initBar() {

        barView = findViewById(R.id.app_top_bar);
        if (barView != null) {
            backIv = barView.findViewById(R.id.include_top_iv_back);
            backIv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
            titleTv = barView.findViewById(R.id.include_top_tv_title);
            optionTv = barView.findViewById(R.id.include_top_tv_right);
        }

    }

    protected void hideBar() {
        if (barView != null) {
            barView.setVisibility(View.GONE);
        }
    }

    protected void showBar() {
        if (barView != null) {
            barView.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 设置title
     *
     * @param title
     */
    protected void setTitle(String title) {
        if (titleTv != null && title != null) {
            titleTv.setText(title);
        }
    }

    /**
     * 隐藏返回键
     */
    protected void hideBack() {
        if (backIv != null) {
            backIv.setVisibility(View.INVISIBLE);
        }
    }

    protected void showLoading(String title) {
        try {
            if (loadingDialog == null) {
                loadingDialog = new LoadingDialog(this);
                loadingDialog.setTitle(title);
                loadingDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        clickable = true;
                    }
                });
                loadingDialog.show();
            } else {
                loadingDialog.setTitle(title);
                loadingDialog.show();
            }
        } catch (Exception e) {

        }
    }

    protected void dismissLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }

    /**
     * 权限申请
     */
    @SuppressLint("CheckResult")
    protected void checkPermissions(String permission) {
        rxPermissions.request(permission)
                .subscribe(granted -> {
                    if (granted) {
                        onPermission(permission, true);
                    } else {
                        onPermission(permission, false);
                    }
                });
    }

    protected void onPermission(String permisstion, boolean isGranted) {

    }

    /**
     * 显示键盘
     *
     * @param et 输入焦点
     */
    public void showInput(final EditText et) {
        et.requestFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);
    }

    /**
     * 隐藏键盘
     */
    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }
}
